<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport ( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModelJAEmployers extends JModel {
	var $_data;
    var $_table;
    var $_pagination;
    var $_fieldList;
    var $_fieldListEdit;
	var $_table_name = 'ja_profiles';
	var $_profile_table = null;	
	
/**
	 * Get list Items by condittion
	 *
	 * @return list items
	 */
	function getItems($where_more='') {
		
		global $mainframe, $jbconfig, $option;
    	
    	$db = JFactory::getDBO ();

		$request = $_REQUEST;
		$filter_field_keys = array();
		if($request){
			$filter_field_keys = array_keys($request);
		}
		
		$statistics = array ();
		$statistics ['created_date'] = JRequest::getVar ( 'filter_duration' );
		
		$limit = $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.limit",	'limit',	'20',	'int' );
		$limitstart = $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.limitstart",	'limitstart',	'0',	'int' );
		
    	$db = JFactory::getDBO();
    	
    	$search	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.search",			'user_search',			'',				'string' );
		$search = trim(JString::strtolower ( $search ));
		
		$is_featured	= $mainframe->getUserStateFromRequest( $option.".jaemployers.is_featured",	'is_featured',		'',	'cmd' );
		$approved	= $mainframe->getUserStateFromRequest( $option.".jaemployers.approved",	'approved',		'',	'cmd' );
		
		$this->getFieldList();
    	$this->getEditFieldList(' and f.frontend_hidden=0');
    	
    	$filter_order = JRequest::getVar('filter_order', 'a.id');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.".jaemployers.filter_order_Dir",	'filter_order_Dir',	"DESC",	'word' );				
    	
    	$where = array();
    	
    	// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
				
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();		
		
		$join_clause_table['emplo'] =  "\n INNER JOIN #__ja_employers as  emplo";
		$join_clause_table['rs'] =  "\n INNER JOIN #__users as rs ";
		
		$join_clause_field['emplo'] = "  ON emplo.user_id=a.user_id ";
		$join_clause_field['rs'] = " ON rs.id=a.user_id ";
		
		if($search){
        	$subwhere [] .= " (rs.username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        	 					" OR rs.email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        						")";
        }
        
		JB_Admin_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search, $subwhere);			
		
        if($is_featured!='' && $is_featured==0){
        	$where_clause[] = ' (	emplo.featured=0 or ISNULL(emplo.featured) )';
        }
        elseif($is_featured==1){
        	$where_clause[] = 'emplo.featured=1' ;
        }
        
		if($approved!='' && $approved==0){
        	$where_clause[] = ' (	a.approved=0 or ISNULL(a.approved) )';
        }
        elseif($approved==1){
        	$where_clause[] = 'a.approved=1' ;
        }                
        
		switch ($statistics['created_date']) 	{
    		case 'today':
    			$where_clause[] = '(DATEDIFF(a.created_date,now())=0)';
    			break;
    		case 'week':
    			$where_clause[] = '(EXTRACT(WEEK FROM a.created_date)=EXTRACT(WEEK FROM now()))';
    			break;	
    		case 'month':
    			$where_clause[] = '(EXTRACT(MONTH FROM a.created_date)=EXTRACT(MONTH FROM now()))';
    			break;
    	}    	
				
		if ($filter_order) {
			$orderby =$filter_order .' '. $filter_order_Dir;
		} else {
			$orderby = " a.id DESC";
		}
		
		
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
        
        /* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );//echo $db->getQuery();exit;
		$total = $db->loadResult ();//print_r($db);exit;
		
		jimport ( 'joomla.html.pagination' );		
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.approved, a.company, rs.id, rs.name, rs.username, rs.email, emplo.ordering" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.id desc';
		$db->setQuery ( $query, $limitstart, $limit );	
					
		$items = $db->loadObjectList ();
		
		return $items;
	}
	
	/**
	 * Return the query is used to retrive all row from database
	 * @return string The query is used 
	 */
	function _buildQuery() {
		
	}
	
	
 	/**
    * @desc Get all fields that will be displayed on edit form
    */
    function getEditFieldList($where = ''){        
        if(!$this->_fieldListEdit){	       
	        $this->_fieldListEdit = getEditFieldList($this->_table_name);
        }   
		return $this->_fieldListEdit ;       
    }
    
    function getFieldList($where=''){    	    	
    	if( !$this->_fieldList){	       
	        $this->_fieldList = getFieldList($this->_table_name); 
    	}
    	return  $this->_fieldList;
    }
    
    
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'ja_employer', 'JobBoardTable' );
		
		}
		return $this->_table;
	}
	
	function &_getProfileTable() {
		if ($this->_profile_table == null) {
			$this->_profile_table = &JTable::getInstance ( 'ja_profiles', 'JobBoardTable' );
		
		}
		return $this->_profile_table;
	}
	
	/**
	 * Get page navigator object
	 * @return 
	 */
	function &getPagination() {
		if ($this->_pagination == null) {
			$this->getItems ();
		}
		return $this->_pagination;
	}
	
	/**
	 * Remove email record
	 * @return Number of removed records
	 */
	function remove() {
		JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		$db = & JFactory::getDBO ();
		$currentUser = & JFactory::getUser ();
		$acl = & JFactory::getACL ();
		$cid = JRequest::getVar ( 'cid', array (), '', 'array' );
		
		JArrayHelper::toInteger ( $cid );
		
		if (count ( $cid ) < 1) {
			JError::raiseError ( 500, JText::_ ( 'Select a User to delete', true ) );
		}
		
		$msg = '';
		if ($cid) {
			foreach ( $cid as $id ) {
				// check for a super admin ... can't delete them
				$objectID = $acl->get_object_id ( 'users', $id, 'ARO' );
				$groups = $acl->get_object_groups ( $objectID, 'ARO' );
				$this_group = strtolower ( $acl->get_group_name ( $groups [0], 'ARO' ) );
				
				$success = false;
				if ($this_group == 'super administrator') {
					$msg = JText::_ ( 'You cannot delete a Super Administrator' );
				} else if ($id == $currentUser->get ( 'id' )) {
					$msg = JText::_ ( 'You cannot delete Yourself!' );
				} else if (($this_group == 'administrator') && ($currentUser->get ( 'gid' ) == 24)) {
					$msg = JText::_ ( 'WARNDELETE' );
				} else {
					$user = & JUser::getInstance ( ( int ) $id );
					$count = 2;
					
					if ($user->get ( 'gid' ) == 25) {
						// count number of active super admins
						$query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
						$db->setQuery ( $query );
						$count = $db->loadResult ();
					}
					
					if ($count <= 1 && $user->get ( 'gid' ) == 25) {
						// cannot delete Super Admin where it is the only one that exists
						$msg = "You cannot delete this Super Administrator as it is the only active Super Administrator for your site";
					} else {
						
						// delete user
						$user->setParam ( 'usertype', 'Guest' );
						$user->save ( true );
						//						$user->delete();
						

						/* Delete employer record*/
						//						$query = "DELETE FROM #__ja_employers WHERE user_id = ". implode(" OR user_id = ", $cid);
						$query = "DELETE FROM #__ja_employers WHERE user_id = $id";
						$db = &JFactory::getDBO ();
						$db->setQuery ( $query );
						$db->query ();
						
						/* Delete permission record */
						$query = "DELETE FROM #__ja_permissions WHERE user_id = $id";
						$db = &JFactory::getDBO ();
						$db->setQuery ( $query );
						$db->query ();
						
						/* Delete profile record */
						$query = "DELETE FROM #__ja_profiles WHERE user_id = $id";
						$db = &JFactory::getDBO ();
						$db->setQuery ( $query );
						$db->query ();
						
						clearDataForEmployer($id);
						
						JRequest::setVar ( 'task', 'remove' );
						JRequest::setVar ( 'cid', $id );
						
					// delete user acounts active sessions
					//$this->logout();
					}
				}
			}
			$row = $this->_getTable ();
			$row->reorder ();
			
			return $msg;
		}
	}
	
	function empl_store() {
		$id = JRequest::getVar ( 'id' );
		JRequest::setVar ( 'employer_id', $id );
		// Initialize variables
		$db = & JFactory::getDBO ();
		if (! $row)
			$row = & $this->getItem ();
		
		if ( JRequest::getVar('begin_date_search_resume') != "" )
			JRequest::setVar('begin_date_search_resume', date( "Y-m-d H:i:s", strtotime( JRequest::getVar('begin_date_search_resume') ) ));
		
		if ( JRequest::getVar('end_date_search_resume') != "" )
			JRequest::setVar('end_date_search_resume', date( "Y-m-d H:i:s", strtotime( JRequest::getVar('end_date_search_resume') ) ));     			
			
		$state = $row->approved;
		$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );	
			
		if (! $row->bind ( $post )) {
			echo "<script> alert('" . $row->getError ( true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		     
		
		if (! $row->store ()) {
			echo "<script> alert('" . $row->getError ( true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		
		$new_state = $row->approved;
		if (($state != $new_state) && ($new_state == '1')) {
			exit ();
			prepare_data ( 'Employer User', $row->user_id );
			initial_employer ( $row->user_id );
		}
		return $row->id;
	
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableja_employers Table object
	 */
	function getProfileItem() {
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		
		$table = & $this->_getProfileTable ();
		$table->_tbl_key = 'user_id';
		// Load the current item if it has been defined
		$edit = JRequest::getVar ( 'view', true );
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		
		if ($edit) {
			$table->load ( $cid [0] );
		}
		
		$item = $table;
		return $item;
	}
	
	function orderItem($item, $movement) {
		$row = &$this->_getTable ();
		$row->load ( $item );
		if (! $row->move ( $movement )) {
			$this->setError ( $row->getError () );
			return false;
		}
		return true;
	}
	function setOrder($items) {
		$str_user_id = implode ( ',', $items );
		$total = count ( $items );
		$row = & $this->_getTable ();
		$db = JFactory::getDBO ();
		$query = "SELECT id FROM #__ja_employers WHERE user_id IN ($str_user_id)";
		
		$db->setQuery ( $query );
		$em_id = $db->loadResultArray ();
		
		$order = JRequest::getVar ( 'ordering', array (), 'post', 'array' );
		JArrayHelper::toInteger ( $order );
		
		// update ordering values
		for($i = 0; $i < $total; $i ++) {
			$row->load ( $items [$i] );
			//			var_dump($order[$i]);exit;
			// track parents
			if ($row->ordering != $order [$i]) {
				$row->ordering = $order [$i];
				if (! $row->store ()) {
					$this->setError ( $row->getError () );
					return false;
				}
			} // if
		} // for
		

		return true;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableja_employers Table object
	 */
	function getItem() {
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		
		$table = & $this->_getTable ();
		$table->_tbl_key = 'id';
		// Load the current item if it has been defined
		$edit = JRequest::getVar ( 'view', true );
		$cid = JRequest::getVar ( 'employer_id', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		
		if ($edit) {
			$table->load ( $cid [0] );
		}
		
		return $table;
	}		
	
	function getInvoices() {
		$filter_invoice_type = JRequest::getVar ( 'filter_invoice_type' );
		require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'japostingplans_invoice.php';
		require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'jasubscriptions_invoice.php';
		require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'models' . DS . 'jacredits_invoice.php';
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		JRequest::setVar ( 'userid', $cid [0] );
		$subs_items = JAJobBoardModelJASubscriptions_Invoice::getItems ();
		$plan_items = JAJobBoardModelJAPostingPlans_Invoice::getItems ();
		$credit_items = JAJobBoardModelJACredits_Invoice::getItems ();
		$items = array ();
		switch (strtolower ( $filter_invoice_type )) {
			case '' :
				$items ['s'] = $subs_items;
				$items ['p'] = $plan_items;
				$items ['c'] = $credit_items;
				break;
			case 's' :
				$items ['s'] = $subs_items;
				break;
			case 'p' :
				$items ['p'] = $plan_items;
				break;
			case 'c' :
				$items ['c'] = $credit_items;
		}
		
		return $items;
	}
	
	function getviewFieldList() {
	
	}
	
	function getCurrentAccInfo() {
		$userid = JRequest::getVar ( 'cid', array (), 'get', 'array' );
		JArrayHelper::toInteger ( $userid );
		$userid = $userid [0];
		$db = JFactory::getDBO ();
		$query = 'SELECT id FROM #__ja_employers WHERE user_id=' . $userid;
		$db->setQuery ( $query );
		$cid = $db->loadResultArray ();
		JRequest::setVar ( 'employer_id', $cid );
		$item = $this->getItem ();
		return $item;
	}
		
	/**
	 * Get list email by list ids
	 *
	 */
	function getEmails() {
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		if (! $cid)
			return '';
		
		$cid = implode ( ',', $cid );
		
		$emails = '';
		
		$db = &JFactory::getDBO ();
		$query = "select email from #__ja_employers where id in ($cid)";
		$db->setQuery ( $query );
		$emails = $db->loadResultArray ( 0 );
		if ($emails) {
			$emails = implode ( ',', $emails );
		}
		return $emails;
	}
	
	/** 
	 * Store configuration item
	 * @param array The post array
	 */
	function store($row = null) {
		$controller = 'japrofiles';
		// Initialize variables
		$db = & JFactory::getDBO ();
		if (! $row)
			$row = & $this->getProfileItem ();
		$state = $row->approved;
		$post = $this->getState ( 'request' );
		
		if (! $row->bind ( $post )) {
			echo "<script> alert('" . $row->getError ( true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		if ($row->spec_field) {
			if (! assign_spec_field ( $controller, $row ))
				return false;
		}
		if ($row->editor_field)
			assign_editor_field($row);
		if (! $row->check ()) {
			return false;
		}
				
		if (! $row->store ()) {
			echo "<script> alert('" . $row->getError ( true ) . "'); window.history.go(-1); </script>\n";
			return false;
		}
		$new_state = $row->approved;
		if (($state != $new_state) && ($new_state == '1')) {
			
			//			prepare_data('Employer User',$row->user_id);
			updateUserType ( JBEMPLOYER_USER, $row->user_id );
			$this->status_changing_email ( $row->id, $row->user_id, 'EmployerApprovedEmail' );
		}
		if (($state != $new_state) && ($new_state == '0')) {
			
			//			prepare_data('Employer User',$row->user_id);
			$this->status_changing_email ( $row->id, $row->user_id, 'EmployerNonApprovedEmail' );
			updateUserType ( 'Guest', $row->user_id );
		}
		$row->checkin ( $row->user_id );
		
		return $row->user_id;
	}
	
	/**
	 * approved one job
	 * 
	 */
	function doblock($block) {
		// Check for request forgeries
		JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		$db = & JFactory::getDBO ();
		$acl = & JFactory::getACL ();
		$currentUser = & JFactory::getUser ();
		
		$cid = JRequest::getVar ( 'cid', array (), '', 'array' );
		
		JArrayHelper::toInteger ( $cid );
		
		if (count ( $cid ) < 1) {
			JError::raiseError ( 500, JText::_ ( 'Select a User to ' . $this->getTask (), true ) );
		}
		foreach ( $cid as $id ) {
			// check for a super admin ... can't delete them
			$objectID = $acl->get_object_id ( 'users', $id, 'ARO' );
			$groups = $acl->get_object_groups ( $objectID, 'ARO' );
			$this_group = strtolower ( $acl->get_group_name ( $groups [0], 'ARO' ) );
			
			$success = false;
			if ($this_group == 'super administrator') {
				$msg = JText::_ ( 'You cannot block a Super Administrator' );
			} else if ($id == $currentUser->get ( 'id' )) {
				$msg = JText::_ ( 'You cannot block Yourself!' );
			} else if (($this_group == 'administrator') && ($currentUser->get ( 'gid' ) == 24)) {
				$msg = JText::_ ( 'WARNBLOCK' );
			} else {
				$user = & JUser::getInstance ( ( int ) $id );
				$count = 2;
				
				if ($user->get ( 'gid' ) == 25) {
					// count number of active super admins
					$query = 'SELECT COUNT( id )' . ' FROM #__users' . ' WHERE gid = 25' . ' AND block = 0';
					$db->setQuery ( $query );
					$count = $db->loadResult ();
				}
				
				if ($count <= 1 && $user->get ( 'gid' ) == 25) {
					// cannot delete Super Admin where it is the only one that exists
					$msg = "You cannot block this Super Administrator as it is the only active Super Administrator for your site";
				} else {
					$user = & JUser::getInstance ( ( int ) $id );
					$user->block = $block;
					$user->save ();
					
					if ($block) {
						
						$msg = JText::_ ( 'Successfully blocked user(s)' );
						// delete user acounts active sessions
					//						$this->logout();
					} else
						$msg = JText::_ ( 'Successfully unblocked user(s)' );
					JRequest::setVar ( 'task', 'block' );
					JRequest::setVar ( 'cid', array ($id ) );
				}
			}
		}
		return $msg;
	}
	
	function getLocation() {
		$db = & JFactory::getDBO ();
		$query = "SELECT id, name FROM #__ja_location WHERE (parent_id = 0 OR ISNULL(parent_id)) AND published = 1";
		$db->setQuery ( $query ); //print_r($db->getQuery($query));exit;
		$locations = $db->loadObjectList ();
		return $locations;
	}
	
	function download() {
		$cid = JRequest::getVar ( 'cid', array (0 ), '', 'array' );
		JArrayHelper::toInteger ( $cid, array (0 ) );
		$table = & $this->_getTable ();
		$table->_tbl_key = 'id';
		$table->load ( $cid [0] );
		$file_name = explode ( '/', $table->file_attachment );
		if ($table->file_attachment) {
			$file = JPATH_SITE . DS . str_replace ( '/', '\\', $table->file_attachment );
			header ( 'Content-type: application/octet-stream' );
			header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ).'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
			readfile ( $file );
		}
	}
	
	function doapprove($task) {
		JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		$db = & JFactory::getDBO ();
		
		$cid = JRequest::getVar ( 'cid', array (), '', 'array' );
		$approve = ($task == 'approve') ? 1 : 0;
		$email_template = ($task == 'approve') ? 'EmployerApprovedEmail' : 'EmployerNonApprovedEmail';
		$new_usertype = ($task == 'approve') ? JBEMPLOYER_USER : 'Guest';
		JArrayHelper::toInteger ( $cid );
		
		if (count ( $cid ) < 1) {
			JError::raiseError ( 500, JText::_ ( 'Select a User to ' . $task (), true ) );
		}
		if (is_array ( $cid ))
			$str_cid = implode ( ',', $cid );
		else
			$str_cid = $cid;
		$query = "UPDATE #__ja_profiles SET approved=$approve WHERE user_id IN ($str_cid)";
		$db->setQuery ( $query );
		$db->query ();
		
		$query = "SELECT user_id,id FROM #__ja_profiles WHERE user_id IN ($str_cid)";
		$db->setQuery ( $query );
		$obj_UserId = $db->loadObjectList ();
		for($i = 0; $i < count ( $obj_UserId ); $i ++) {
			updateUserType ( $new_usertype, $obj_UserId [$i]->user_id );
			$this->status_changing_email ( $obj_UserId [$i]->id, $obj_UserId [$i]->user_id, $email_template );
		}
		
		$msg = ($task == 'approve') ? JText::_ ( 'Successfully approved profile(s). User(s) can now perform their permission on the site.' ) : JText::_ ( 'Successfully disapproved the profile(s). User(s) have not been permitted to perform any activities on the site.' );
		return $msg;
	}
	
	function status_changing_email($profile_id, $user_id, $email_template) {
		$user = JFactory::getUser ( $user_id );
		$arr_link = array ();
		$arr_link ['users'] = $user_id;
		$arr_link ['ja_profiles'] = $profile_id;
		$mail = get_EmailTemplate ( $arr_link, $email_template );
		if ($mail) {
			sendmail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
		}
	}
	
	function remove_attach() {
		remove_attach ( 'ja_profiles' );
	
	}
}
?>
